package org.chen.produce;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.constant.ArticleStatusEnum;
import org.chen.common.constant.VideoStatusEnum;
import org.chen.domain.dto.MessageData;
import org.chen.domain.entity.VideoArticle;
import org.chen.domain.entity.VideoTask;
import org.chen.mapper.ArticleMapper;
import org.chen.mapper.VideoTaskMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class TaskMessageProducer {
    
    private final RabbitTemplate rabbitTemplate;
    private final VideoTaskMapper taskMapper;
    private final ArticleMapper articleMapper;
    
    private static final String EXCHANGE_NAME = "video.task.exchange";
    private static final String ROUTING_KEY = "video.task.generate";
    
    public void sendTaskMessage(MessageData messageData) {
        try {
            rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY, messageData);
            log.info("Sent task message for task: {}", messageData.getVideoTask().getId());
        } catch (Exception e) {
            log.error("Failed to send task message: {}", messageData.getVideoTask().getId(), e);
            // 如果消息发送失败，可以考虑重试或者将任务标记为失败
            handleMessageSendFailure(messageData);
        }
    }
    
    private void handleMessageSendFailure(MessageData messageData) {
        // TODO: 实现消息发送失败的处理逻辑
        // 将任务状态更新为失败
        VideoTask videoTask = messageData.getVideoTask();
        videoTask.setStatus(VideoStatusEnum.FAILED.getCode());
        videoTask.setErrorMessage("请重试");
        taskMapper.updateById(videoTask);

        VideoArticle article = articleMapper.selectById(videoTask.getArticleId());
        article.setStatus(ArticleStatusEnum.FAILED.getCode());
        articleMapper.updateById(article);
    }

    /**
     * 批量发送任务消息
     */
    public void batchSendTaskMessages(List<MessageData> messageDataList) {
        if (messageDataList == null || messageDataList.isEmpty()) {
            return;
        }

        int successCount = 0;
        List<String> failedTaskIds = new ArrayList<>();

        for (MessageData messageData : messageDataList) {
            try {
                rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY, messageData);
                successCount++;
            } catch (Exception e) {
                log.error("Failed to send task message: {}", messageData.getVideoTask().getId(), e);
                failedTaskIds.add(messageData.getVideoTask().getId());
                // 处理失败
                handleMessageSendFailure(messageData);
            }
        }

        log.info("批量发送任务消息完成，成功: {}，失败: {}", successCount, failedTaskIds.size());
    }
}